package com.digital.smartgrow.service.business.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.digital.smartgrow.common.util.BeanCopyUtil;
import com.digital.smartgrow.common.util.WebTool;
import com.digital.smartgrow.dto.business.StartUpDto;
import com.digital.smartgrow.dto.business.UpJobPageDTO;
import com.digital.smartgrow.entity.business.UpBase;
import com.digital.smartgrow.entity.business.UpJob;
import com.digital.smartgrow.entity.business.UpJobLog;
import com.digital.smartgrow.entity.business.UpProcessLog;
import com.digital.smartgrow.entity.datacenter.Teacher;
import com.digital.smartgrow.entity.export.ExportApprove;
import com.digital.smartgrow.entity.notice.WaitNotice;
import com.digital.smartgrow.entity.process.UpProcess;
import com.digital.smartgrow.entity.process.UpProcessItem;
import com.digital.smartgrow.service.business.*;
import com.digital.smartgrow.service.datacenter.TeacherService;
import com.digital.smartgrow.service.export.ExportApproveService;
import com.digital.smartgrow.service.notice.WaitNoticeService;
import com.digital.smartgrow.service.process.UpProcessItemService;
import com.digital.smartgrow.service.process.UpProcessService;
import com.digital.smartgrow.vo.businesscenter.MeUpJobInfoVo;
import com.digital.smartgrow.vo.businesscenter.MeUpJobVo;
import com.digital.smartgrow.vo.businesscenter.UpJobVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by SunYuechao on 2022/7/13 下午2:35
 */
@Service
public class UpAskServiceImpl implements UpAskService {
    @Autowired
    private UpJobService upJobService;
    @Autowired
    private UpJobLogService upJobLogService;
    @Autowired
    private UpProcessItemService processItemService;
    @Autowired
    private UpProcessService processService;
    @Autowired
    private UpProcessLogService processLogService;
    @Autowired
    private UpBaseService baseService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private WaitNoticeService noticeService;
    @Autowired
    private ExportApproveService exportApproveService;


    /**
     * 根据选择的晋级ID 获取下一个审批流程是角色，还是人员
     *
     * @param upJobId
     * @return
     */
    @Override
    public Object getIsRole(Integer upJobId) {
        UpProcessLog log = getNextLog(upJobId);
        Map<String, Integer> map = new HashMap<>();
        map.put("isRole", log.getIsRole());
        map.put("checkId", log.getCheckId());
        return map;
    }


    /**
     * 开始申报数据，生成申报数据、基础数据，及流程数据
     *
     * @param upId 申报项ID
     * @return
     */
    @Override
    public Object startUp(Integer upId) {
        Teacher user = WebTool.getCurrentUser();
        UpJob upJob = upJobService.getInfo(upId);
        UpProcess process = processService.getById(upJob.getProcess());
        /**===========保存晋级申请表  标志进度为 待审批* ==========**/
        Integer jobLogId = saveJobLog(user, upJob,null);
        /**===========保存基础数据表==========**/
        UpBase upBase = new UpBase();
        upBase.setUserId(user.getId());
        upBase.setJobLogId(jobLogId);
        baseService.save(upBase);
        Integer baseId = upBase.getId();
        //增加申报明细和基本表关联
//        UpJobLog byId = upJobLogService.getById(jobLogId);
//        byId.setUpBaseId(baseId);
//        upJobLogService.updateById(byId);


        /**===========保存晋级申请表  标志进度为 待审批==========**/
        List<UpProcessItem> processItems = processItemService.list(Wrappers.<UpProcessItem>query()
                .lambda().eq(UpProcessItem::getSuperCode, process.getId()));
        //saveProcessLog(processItems, upJob, user,jobLogId, role, roleUserId, people);

        Map<String, Integer> map = new HashMap<>();
        map.put("jobLogId", jobLogId);//晋升表ID
        map.put("baseId", baseId);//申请单ID
        //map.put("processLogId", processLogId);//流程ID
        return map;
    }
    @Override
    public Object startUpOne(StartUpDto startUpDto) {
        Teacher user = WebTool.getCurrentUser();
        UpBase upBase = startUpDto.getUpBase();
        Integer upId = startUpDto.getUpJobId();
        UpJob upJob = upJobService.getInfo(upId);
        UpProcess process = processService.getById(upJob.getProcess());
        /**===========保存晋级申请表  标志进度为 待审批==
         * 如果是未审批(编辑状态)不生成新的申请流程[防止在显示的时候，脏数据的出现]========**/
        Integer jobLogId =null;
        //判断是否需要新的审批流程
        Boolean isNewProcess=true;
        //获取本地表中是否有，不能依赖传过来的参数---划重点
        UpBase upBaseTable = baseService.getById(upBase.getId());
        if(upBaseTable.getJobLogId()!=null){
            UpJobLog jobLog = upJobLogService.getById(upBaseTable.getJobLogId());
            if(jobLog!=null&&jobLog.getStatus()==0){
                isNewProcess=false;
            }else if(jobLog!=null&&jobLog.getStatus()==1){
                return "审核中，不允许修改";
            }else if(jobLog!=null&&jobLog.getStatus()==2){
                return "审核已通过，不允许修改";
            }else if(jobLog!=null&&jobLog.getStatus()==-2){
                return "审核未通过，不允许再次申请";
            }
        }

        jobLogId=isNewProcess?saveJobLog(user, upJob,upBase.getId()):upBaseTable.getJobLogId();
        /**===========保存基础数据表==========**/
        upBase.setUserId(user.getId());
        //填报时间
        upBase.setUpdateTime(LocalDateTime.now());
        //将最新审批流传入基础数据表
        upBase.setJobLogId(jobLogId);
        baseService.updateById(upBase);
  //      Integer baseId = upBase.getId();
        //增加申报明细和基本表关联
//        UpJobLog byId = upJobLogService.getById(jobLogId);
//        byId.setUpBaseId(baseId);
//        upJobLogService.updateById(byId);


        /**===========保存晋级申请表  标志进度为 待审批==========**/
        if(isNewProcess){
            List<UpProcessItem> processItems = processItemService.list(Wrappers.<UpProcessItem>query()
                    .lambda().eq(UpProcessItem::getSuperCode, process.getId()));
            //生成流程
            Integer role = startUpDto.getRole();
            Integer roleUserId = startUpDto.getRole();
            Integer people = startUpDto.getPeople();
            saveProcessLog(processItems, upJob, user,jobLogId,role,roleUserId,people);
        }


//        Map<String, Integer> map = new HashMap<>();
//        map.put("jobLogId", jobLogId);//晋升表ID
//        map.put("baseId", baseId);//申请单ID
        //map.put("processLogId", processLogId);//流程ID
        return "申报成功";
    }



    /**
     * 打回重新申报
     *
     *
     * @param upId
     * @param jobLogIdOld
     * @return
     */
    @Override
    public Object restUp(Integer upId, Integer jobLogIdOld) {
        Teacher user = WebTool.getCurrentUser();
        UpJob upJob = upJobService.getInfo(upId);
        UpProcess process = processService.getById(upJob.getProcess());
        /**===========保存晋级申请表  标志进度为 待审批==========**/
        Integer jobLogId = saveJobLog(user, upJob,null);
        /**===========保存基础数据表==========**/
        QueryWrapper<UpBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", user.getId());
        queryWrapper.eq("jobLogId", jobLogIdOld);
        UpBase old = baseService.getOne(queryWrapper);
        UpBase upBase = old;
        upBase.setId(null);
        upBase.setUserId(user.getId());
        upBase.setJobLogId(jobLogId);
        //填报时间
        upBase.setUpdateTime(LocalDateTime.now());
        baseService.save(upBase);
        Integer baseId = upBase.getId();
        /**===========保存晋级申请表  标志进度为 待审批==========**/
        List<UpProcessItem> processItems = processItemService.list(Wrappers.<UpProcessItem>query()
                .lambda().eq(UpProcessItem::getSuperCode, process.getId()));
        //saveProcessLog(processItems, upJob, user,jobLogId, role, roleUserId, people);

        Map<String, Integer> map = new HashMap<>();
        map.put("jobLogId", jobLogId);//晋升表ID
        map.put("baseId", baseId);//申请单ID
        //map.put("processLogId", processLogId);//流程ID
        return map;
    }
    @Override
    public List<MeUpJobVo> myJobList(UpJobPageDTO upJobPageDTO) {
        Page<UpJob> page = new Page<>(upJobPageDTO.getPageNum(), upJobPageDTO.getPageSize());
        QueryWrapper<UpJob> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq( "status", 1);
        queryWrapper.eq(StringUtils.isNotBlank(upJobPageDTO.getArchives()), "archives", upJobPageDTO.getArchives());
        queryWrapper.eq(StringUtils.isNotBlank(upJobPageDTO.getYear()), "year", upJobPageDTO.getYear());

        Page<UpJob> page1 = upJobService.page(page, queryWrapper);
        List<UpJob> records = page1.getRecords();
        List<MeUpJobVo> lists=new ArrayList<>();
        Teacher user = WebTool.getCurrentUser();
        for(int i=0;i<records.size();i++) {
            UpJob j=records.get(i);
            UpBase upBase = baseService.lambdaQuery()
                    .eq(UpBase::getUserId, user.getId())
                    .eq(UpBase::getJobId, j.getId()).one();
            if(upBase!=null){
                MeUpJobVo meUpJobVo = BeanCopyUtil.copyProperties(j, MeUpJobVo::new);
                meUpJobVo.setUpBaseId(upBase.getId());
                meUpJobVo.setUpTime(upBase.getUpdateTime().toString().replace("T", " "));
                //获取最后结果
                List<UpJobLog> list = upJobLogService.lambdaQuery()
                        .eq(UpJobLog::getUpJobCode, j.getId())
                        .eq(UpJobLog::getUserCode, user.getEmployeeId())
                        .list();
                //排序
                list = list.stream().sorted(Comparator.comparingInt(UpJobLog::getId)).collect(Collectors.toList());
                //获取最后一个状态
                meUpJobVo.setStatus(list.get(list.size()-1).getStatus());
                lists.add(meUpJobVo);
            }

        }
        return lists;
    }

    @Override
    public MeUpJobInfoVo myJobInfo(Integer upBaseId) {
        Teacher user = WebTool.getCurrentUser();
        MeUpJobInfoVo infoVo=new MeUpJobInfoVo();
        UpBase upBase = baseService.getById(upBaseId);
        infoVo.setUpBase(upBase);
        List<UpJobLog> list = upJobLogService.lambdaQuery()
                .eq(UpJobLog::getUpBaseId, upBaseId)
                .eq(UpJobLog::getUserCode, user.getEmployeeId())
                .list();
        //排序
        list = list.stream().sorted(Comparator.comparingInt(UpJobLog::getId)).collect(Collectors.toList());
        for(int i=0;i<list.size();i++){
            List<UpProcessLog> processLogList = processLogService.lambdaQuery()
                    .eq(UpProcessLog::getUpJobLogId, list.get(i).getId())
                    .eq(UpProcessLog::getUserId, user.getId())
                    .list();
            processLogList = processLogList.stream().sorted(Comparator.comparingInt(UpProcessLog::getId)).collect(Collectors.toList());
            list.get(i).setProcessLogList(processLogList);

        }
        infoVo.setList(list);

        return infoVo;
    }

    @Override
    public List<UpJobVo> jobList(UpJobPageDTO upJobPageDTO) {
        Page<UpJob> page = new Page<>(upJobPageDTO.getPageNum(), upJobPageDTO.getPageSize());
        QueryWrapper<UpJob> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq( "status", 1);
        queryWrapper.eq(StringUtils.isNotBlank(upJobPageDTO.getArchives()), "archives", upJobPageDTO.getArchives());
        queryWrapper.eq(StringUtils.isNotBlank(upJobPageDTO.getYear()), "year", upJobPageDTO.getYear());

        Page<UpJob> page1 = upJobService.page(page, queryWrapper);
        List<UpJob> records = page1.getRecords();
        List<UpJobVo> upJobVos = BeanCopyUtil.copyListProperties(records, UpJobVo::new);
        Teacher user = WebTool.getCurrentUser();
        for(int i=0;i<upJobVos.size();i++) {
            UpJobVo j=upJobVos.get(i);
            Integer upJobId = j.getId();
            String userCode = user.getEmployeeId();
            List<UpJobLog> list = upJobLogService.lambdaQuery()
                    .eq(UpJobLog::getUpJobCode, upJobId)
                    .eq(UpJobLog::getUserCode, userCode)
                    .list();



            /**
             * 申请状态：状态("审核状态 新申请-3，待审核：0，审核中：1，通过：2，打回重新申报：-1,不通过：-2")
             *         1、新申请   -3，获取base
             *         2、编辑（可申请时间内，进行修改）0，-1 返回base
             *         3、不可编辑 1、2，-2 返回base
             *         （时间交给前端判断）
             */

            //时间比较
//            Date date = new Date();
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//            String today = format.format(date);
//            String endTime = j.getEndTime();
//            long time1 = 0;
//            long time2 = 0;
//            try {
//                time1 = format.parse(today).getTime();
//                time2 = format.parse(endTime).getTime();
//            } catch (ParseException e) {
//                //throw new RuntimeException(e);
//            }
//            boolean time = time1<time2?true:false;
            boolean time=true;
            if(list.size()>=1&&time){
                UpJobLog upJobLog = list.get(list.size() - 1);
                //申报日志审核状态：待审核：0，审核中：1，通过：2，不通过：-1,打回 -3
                Integer status = upJobLog.getStatus();
                upJobVos.get(i).setMeStatus(status);
                Integer jobLogId = upJobLog.getId();
                upJobVos.get(i).setUpJobLogId(jobLogId);
                UpBase upBase = baseService.lambdaQuery()
                        .eq(UpBase::getUserId, user.getId())
                        .eq(UpBase::getJobLogId, jobLogId).one();
                if(upBase!=null){
                    upJobVos.get(i).setUpBase(upBase);
                }

//                if(status==0){//可编辑状态
//                    upJobVos.get(i).setMeStatus(1);
//                }else if(status==-1&&time){
//                    upJobVos.get(i).setMeStatus(-1);
//                }else{
//                    upJobVos.get(i).setMeStatus(2);
//                }
//                Integer jobLogId = upJobLog.getId();
//                upJobVos.get(i).setUpJobLogId(jobLogId);
//                UpBase upBase = baseService.lambdaQuery()
//                        .eq(UpBase::getUserId, user.getId())
//                        .eq(UpBase::getJobLogId, jobLogId).one();
//                if(upBase!=null){
//                    upJobVos.get(i).setUpBase(upBase);
//                }
                //upJobVos.get(i).setUpBaseId(list.get(0).getUpBaseId());
            }else {
                //新申请
                upJobVos.get(i).setMeStatus(-3);
                upJobVos.get(i).setUpJobLogId(null);
                //TODO 生成新ID
                upJobVos.get(i).setUpBase(null);
            }
//                    List<Dictionary> dictionaryList = dictionaryService.lambdaQuery()
//                    .eq(Dictionary::getStatus, 1)
//                    .eq(Dictionary::getDeleted, 0)
//                    .list();
            //获取第一审批信息
            Integer processId = j.getProcess();
            UpProcessItem upProcessItem = processItemService.lambdaQuery().eq(UpProcessItem::getSuperCode, processId)
                    .eq(UpProcessItem::getMorder, 0).one();
            upJobVos.get(i).setIsRole(upProcessItem.getIsRole());
            upJobVos.get(i).setRole(upProcessItem.getRole());
            upJobVos.get(i).setPeople(upProcessItem.getPeople());

        }

        return upJobVos;
    }



    /**
     * 通过审批，并指定下一个审批人
     *
     * @param jobLogId
     * @param checkId
     * @return
     */
    @Override
    public Object updateProcess(Integer jobLogId, Integer checkId,String checkContent) {
        UpProcessLog currentLog = this.getCurrentLog(jobLogId);
        if(currentLog==null){
            return "还未到此审批步骤";
        }
        //审批完毕并通过审核
        currentLog.setCheckStatus(1);
        currentLog.setCheckReturn(2);
        currentLog.setAtfId(checkId);
        currentLog.setCheckContent(checkContent);
        currentLog.setCheckTime(LocalDateTime.now());
        processLogService.updateById(currentLog);
        UpProcessLog nextLog = this.getNextLog(jobLogId);
        //设置通知完毕
        /******更新审评总表******/
        UpJobLog jobLog = upJobLogService.getById(currentLog.getUpJobLogId());
        jobLog.setCheckStep(currentLog.getCheckStep());
        jobLog.setStatus(1);//审核状态 待审核：0，审核中：1，通过：2，打回重新申报：-1,不通过：-2

        upJobLogService.updateById(jobLog);
        /******更新专家审核表******/
        upexportApprove(1,jobLog);
       // updateNotice(WebTool.getCurrentUser().getId(), currentLog.getId());
        //判定是否之前已经指定
        if (nextLog == null) {
            /******更新审评总表******/
            //UpJobLog jobLog = upJobLogService.getById(currentLog.getUpJobId());
            jobLog.setStatus(2);//审核状态 待审核：0，审核中：1，通过：2，打回重新申报：-1,不通过：-2
            upJobLogService.updateById(jobLog);
            /******更新专家审核表******/
            upexportApprove(2,jobLog);
            /****发消息***/
            //setNotice(checkId,currentLog.getUserId(),"审批通过");
            return "审核已全部通过，不需要指定下一个审批人";
        }
        //审核通过，系统已固定，无法指定下一个审批人
        if (nextLog.getCheckId() == null) {
            nextLog.setCheckId(checkId);
            nextLog.setCheckName(teacherService.getInfo(checkId).getName());
            processLogService.updateById(nextLog);
            //申报表更改状态
            /****发消息***/
            //setNotice(checkId,nextLog.getId(),"待审核");
            return "审核通过，并指定下一个审批人";

        }
        /****发消息***/
        //如果是自己审批自己，变更通知
//        if(currentLog.getUserId()==WebTool.getCurrentUser().getId()){
//            setNotice(checkId,nextLog.getId(),"职称申报已提交");
//        }else {
//            setNotice(checkId,nextLog.getId(),"待审核");
//        }
        return "审核通过，系统已固定，无法指定下一个审批人";

    }

    /**
     * 打回
     *
     * @param jobLogId
     * @param checkContent
     * @return
     */
    @Override
    public Object callBackProcess(Integer jobLogId, String checkContent) {
        UpProcessLog currentLog = this.getCurrentLog(jobLogId);
        if(currentLog==null){
            return "还未到此审批步骤";
        }
        //打回
        /******更新审评总表******/
        UpJobLog jobLog = upJobLogService.getById(currentLog.getUpJobLogId());
        jobLog.setCheckStep(currentLog.getCheckStep());
        jobLog.setStatus(-1);//通过 1、不通过 -1、审核中 0
        upJobLogService.updateById(jobLog);
        /******更新专家审核表******/
        upexportApprove(-1,jobLog);

        currentLog.setCheckStatus(1);
        currentLog.setCheckReturn(-1);
        currentLog.setCheckContent(checkContent);
        currentLog.setCheckTime(LocalDateTime.now());
        processLogService.updateById(currentLog);
        /****发消息***/
       // setNotice(jobLog.getId(),currentLog.getUserId(),"审批被打回，请重新申报");
        return "打回完成";
    }

    /**
     * 拒绝
     *
     * @param jobLogId
     * @param checkContent
     * @return
     */
    @Override
    public Object deleteProcess(Integer jobLogId, String checkContent) {
        UpProcessLog currentLog = this.getCurrentLog(jobLogId);
        if(currentLog==null){
            return "还未到此审批步骤";
        }
        //拒绝
        /******更新审评总表******/
        UpJobLog jobLog = upJobLogService.getById(currentLog.getUpJobLogId());
        jobLog.setCheckStep(currentLog.getCheckStep());
        jobLog.setStatus(-2);//通过 1、不通过 -1、审核中 0
        upJobLogService.updateById(jobLog);
        /******更新专家审核表******/
        upexportApprove(-2,jobLog);

        currentLog.setCheckStatus(1);
        currentLog.setCheckReturn(-2);
        currentLog.setCheckContent(checkContent);
        currentLog.setCheckTime(LocalDateTime.now());
        processLogService.updateById(currentLog);

        /****发消息***/
        //setNotice(jobLog.getId(),currentLog.getUserId(),"审批被拒绝");

        return "拒绝完成";
    }

    /**
     * 更新专家中的审核状态
     * @param status
     */
   private void upexportApprove(Integer status,UpJobLog jobLog ){
       ExportApprove one = exportApproveService.lambdaQuery()
               .eq(ExportApprove::getUserCode,jobLog.getUserCode() )
               .eq(ExportApprove::getUpJobId,jobLog.getUpJobCode() )
               .eq(ExportApprove::getUpJobLogId,jobLog.getId())
               .eq(ExportApprove::getUpBaseId, jobLog.getUpBaseId())
               .one();
       if(one!=null){
           one.setIsProcess(status);
           exportApproveService.updateById(one);
       }

   }

    /**
     * 下发审核通知
     * @param userId 通知人
     * @param noticeId 消息ID
     */
    private void setNotice(Integer userId,Integer noticeId,String noticeContent){
        WaitNotice notice=new WaitNotice();
        notice.setUserId(userId);
        notice.setNoticeType(1);
        notice.setNoticeId(noticeId);
        notice.setNoticeContent(noticeContent);
        notice.setStatus(0);
        noticeService.save(notice);
    }

    /**
     * 更新已处理审核通知
     * @param userId 通知人
     * @param noticeId 消息ID
     */
    private void updateNotice(Integer userId,Integer noticeId){
        QueryWrapper<WaitNotice> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", userId);
        wrapper.eq("noticeId", noticeId);
        wrapper.eq("noticeType", 1);
        WaitNotice one = noticeService.getOne(wrapper);
        one.setStatus(1);
        one.setNoticeContent("审核完毕");
        noticeService.updateById(one);
    }

    /**
     * 生成审批流明细程表
     *
     * @param processItems
     * @param upJob
     * @param role
     * @param roleUserId
     * @param people
     * @return
     */
    private void saveProcessLog(List<UpProcessItem> processItems, UpJob upJob, Teacher user, Integer jobLogId, Integer role, Integer roleUserId, Integer people) {
        //排序---看看能否用上
        List<UpProcessItem> listSort = processItems.stream().filter(bean -> bean != null && bean.getMorder() != null)
                .sorted(Comparator.comparing(UpProcessItem::getMorder)).collect(Collectors.toList());

        for (int i = 0; i < listSort.size(); i++) {
            UpProcessItem processItem = listSort.get(i);
            UpProcessLog log = new UpProcessLog();

            log.setUserId(user.getId()); //被审批人
            log.setUserName(user.getName());
            log.setUpJobId(upJob.getId());//发起流程ID
            log.setUpJobLogId(jobLogId);//明细ID
            log.setUpJobName(upJob.getName());
            log.setProcessName(listSort.get(i).getName());
            log.setIsRole(listSort.get(i).getIsRole());

            //确定审批人 0 角色  1 自由人
            if (listSort.get(i).getIsRole() == 1) {
                //设计时，是否填写自由人
                if (listSort.get(i).getPeople() != null) {
                    log.setCheckId(listSort.get(i).getPeople());//获取自由人ID（如果没填，null）
                    log.setCheckName(teacherService.getInfo(listSort.get(i).getPeople()).getName());
                }
            } else {
                //设计时，是否填写自由人
                if (listSort.get(i).getRole() != null) {
                    log.setCheckId(listSort.get(i).getRole());//获取自由人ID（如果没填，null）
                    log.setCheckName(teacherService.getInfo(listSort.get(i).getRole()).getName());
                }
            }
            //前后审批人ID
            if (i == 0) {
                log.setPreId(null);
                log.setAtfId(null);
            } else {
                log.setPreId(listSort.get(i - 1).getPeople());
                if (i < listSort.size()-1) {
                    log.setAtfId(listSort.get(i + 1).getPeople());
                }
            }
            //第一审批人
            if (i == 0) {
                if(role==0){
                    log.setCheckId(roleUserId);//获取自由人ID（如果没填，null）
                    log.setCheckName(teacherService.getInfo(roleUserId).getName());
                }else{
                    log.setCheckId(people);//获取自由人ID（如果没填，null）
                    log.setCheckName(teacherService.getInfo(people).getName());
                }
            }


            log.setCheckStep(i);//步骤按 0-1  *****
            //log.setCheckStatus(0); //默认空，不触发通知
            //第一节点审批人为自己，为后期打回做准备
//            if(i==0){
//                log.setCheckStatus(1);
//                log.setCheckReturn(1);
//            }

            processLogService.save(log);

        }
    }

    /**
     * 保存晋级申请表,返回晋级ID
     *
     * @param user
     * @param upJob
     * @return
     */
    private Integer saveJobLog(Teacher user, UpJob upJob,Integer baseId) {
        UpJobLog jobLog = new UpJobLog();
        jobLog.setName(user.getName() + "-" + upJob.getName());
        jobLog.setUserCode(user.getEmployeeId());
        jobLog.setUserName(user.getName());
        jobLog.setGender(user.getGender());
        jobLog.setFaculty(user.getCompany());//所在单位-》所属院系
        jobLog.setSeries(upJob.getSeries());
        jobLog.setMajor(upJob.getMajor());
        jobLog.setUpPost(upJob.getUpPost());
        jobLog.setUpLevel(upJob.getUpLevel());
        jobLog.setYear(upJob.getYear());
        jobLog.setStartTime(upJob.getStartTime());
        jobLog.setEndTime(upJob.getEndTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String  format= sdf.format(new Date());
        jobLog.setUpTime(format);
        jobLog.setStatus(0);//待审核：0，审核中：1，通过：2，不通过：-1
        jobLog.setUpJobCode(upJob.getId());
        jobLog.setCheckStep(0);//审核步骤，0 申报 1 第一次审核，以此类推
        //冗余关联
        jobLog.setUpBaseId(baseId);

        if (upJobLogService.save(jobLog)) {
           return jobLog.getId();
            //return 1;
        } else {
            return null;
        }
    }

    /**
     * 获取前一个审批流程步骤
     *
     * @param upJobId
     * @return
     */
    private UpProcessLog getBefLog(Integer upJobId) {

        UpProcessLog one = getCurrentLog(upJobId);
        int step = one.getCheckStep() - 1;
        QueryWrapper<UpProcessLog> logQueryWrapper = new QueryWrapper<>();
        logQueryWrapper.eq("upJobId", upJobId);
        logQueryWrapper.eq("checkStep", step);
        return processLogService.getOne(logQueryWrapper);
    }

    /**
     * 获取下一个审批流程步骤
     *
     * @param upJobId
     * @return
     */
    private UpProcessLog getNextLog(Integer upJobId) {

        UpProcessLog one = getCurrentLog(upJobId);
        int step = one.getCheckStep() + 1;
        QueryWrapper<UpProcessLog> logQueryWrapper = new QueryWrapper<>();
        logQueryWrapper.eq("upJobId", upJobId);
        logQueryWrapper.eq("checkStep", step);
        return processLogService.getOne(logQueryWrapper);
    }

    /**
     * 获取当前审批流程步骤
     *
     * @param upJobId
     * @return
     */
    private UpProcessLog getCurrentLog(Integer upJobId) {

        QueryWrapper<UpProcessLog> logQueryWrapper = new QueryWrapper<>();
        logQueryWrapper.eq("upJobId", upJobId);
        logQueryWrapper.eq("checkId", WebTool.getCurrentUser().getId());
        UpProcessLog one = processLogService.getOne(logQueryWrapper);
        UpJobLog jobLog = upJobLogService.getById(one.getUpJobLogId());
        if(one.getCheckStep()-jobLog.getCheckStep()==1){
            return one;
        }else{
            return null;
        }

    }
}
